package com.leetcode;

import java.util.Scanner;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No29
 * @description
 * @date 2021/3/13 下午6:16
 */
public class No29 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请分别输入被除数和除数（除数不能为0），两个数字之间至少空一格");
        int dividend = sc.nextInt();
        int divisor = sc.nextInt();
        int quotient = divide(dividend,divisor);
        System.out.println( dividend + "/" + divisor + "的结果为：" + quotient);

    }

    public static int divide(int dividend, int divisor) {
        // 除数为0
        if(dividend == 0){
            return 0;
        }
        if(dividend == Integer.MIN_VALUE && divisor == -1){
            return Integer.MAX_VALUE;
        }
        // 符号是否相同
        boolean flag = (dividend ^ divisor) < 0;
        long t = Math.abs((long) dividend);
        long d = Math.abs((long)divisor);
        int res = 0;
        for (int i = 31; i >= 0 ; --i) {
            // 找出足够大的数2^n*divisor
            if((t >> i) >= d){
                // 2的i次
                res += 1 << i;
                // 将被除数减去2^n*divisor
                t -= d << i;
            }
        }
        return flag ? -res : res;
    }

}
